import { FC, useEffect, useRef, ReactElement, memo, useState } from 'react'
import type { FormInstance } from 'antd'
import { Modal, Form, Input, Select, TreeSelect, message } from 'antd'
import { connect, Dispatch, EvaluationStateType } from 'umi'

import './index.less'
const { Option } = Select
const { TreeNode } = TreeSelect
const { TextArea } = Input

interface IProps {
  visible: boolean
  hide: () => any
  dispatch: Dispatch
  evaluationModel: EvaluationStateType
  update: () => any
}
interface FormValues {
  [name: string]: any
}

const AddEvaluationPage: FC<IProps> = ({
  visible,
  dispatch,
  hide,
  evaluationModel,
  update
}): ReactElement => {
  const formRef = useRef<FormInstance>(null)

  const { criteriaList, gradeList, unitList } = evaluationModel

  const handleOk = () => {
    formRef.current?.submit()
  }
  const handleCancel = () => {
    hide()
    formRef.current?.resetFields()
  }
  const onFinish = (values: FormValues) => {
    const { unitCode, grade } = values
    dispatch({
      type: 'evaluationModel/function_addEvaluationInfo',
      payload: {
        ...values,
        unitCode: unitCode.join(','),
        grade: grade.join(',')
      },
      callback: (response) => {
        if (response.code === 200) {
          message.success('新增成功')
          handleCancel()
          update()
        } else {
          message.warning(response.msg)
        }
      }
    })
  }

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo)
  }

  // 查询评价指标
  const getCriteriaInfo = () => {
    dispatch({
      type: 'evaluationModel/function_getCriteriaInfo',
      payload: {}
    })
  }

  const gradeChange = (value: string[]) => {
    let temp: string[]
    if (value.length && value.lastIndexOf('') === value.length - 1) {
      temp = ['']
      getUnitInfo('')
    } else if (!value.length) {
      temp = []
    } else if (value.length == gradeList.length) {
      temp = ['']
      getUnitInfo('')
    } else {
      temp = value.filter((item) => item)
      getUnitInfo(temp.join(','))
    }

    formRef.current?.setFieldsValue({
      grade: temp
    })
  }

  const renderTree = (data: any[]) => {
    return data.map((item) => {
      if (item.children?.length) {
        return (
          <TreeNode value={item.code} title={item.name} key={item.code}>
            {renderTree(item.children)}
          </TreeNode>
        )
      } else {
        return (
          <TreeNode
            value={item.code}
            title={item.name}
            key={item.code}
          ></TreeNode>
        )
      }
    })
  }

  // 查询学段
  const getGradeInfo = () => {
    dispatch({
      type: 'evaluationModel/function_getGradeInfo',
      payload: {}
    })
  }

  // 查询机构
  const getUnitInfo = (grade?: string) => {
    dispatch({
      type: 'evaluationModel/function_getUnitInfo',
      payload: { grade }
    })
  }

  const onChange = (newValue: any[]) => {
    const unitCode = newValue.map((item) => item.value)
    formRef.current?.setFieldsValue({
      unitCode
    })
  }

  // 获取机构code
  const getCode = (arr: any[]) => {
    var codesList: any[] = []
    function fn(arr: any[]) {
      arr.forEach((item) => {
        codesList.push(item.code)
        if (item.children) {
          fn(item.children)
        }
      })
    }
    fn(arr)
    return codesList
  }

  useEffect(() => {
    if (visible) {
      getCriteriaInfo()
      getGradeInfo()
      getUnitInfo('')
    }
  }, [visible])

  useEffect(() => {
    var codeArr = getCode(unitList)
    formRef.current?.setFieldsValue({
      unitCode: codeArr
    })
  }, [unitList])
  return (
    <>
      <Modal
        title="添加评价信息"
        open={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        width="60%"
        okText="确认"
        cancelText="取消"
        bodyStyle={{
          height: `${window.innerHeight * 0.7}px`,
          overflowY: 'auto'
        }}
        maskClosable={false}
      >
        <Form
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          initialValues={{ grade: [''], status: '1' }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          ref={formRef}
        >
          <Form.Item
            label="名称"
            name="name"
            rules={[{ required: true, message: '请输入名称!' }]}
          >
            <Input placeholder="请输入名称" />
          </Form.Item>

          <Form.Item label="内容" name="content">
            <TextArea rows={3} placeholder="请输入内容" />
          </Form.Item>

          <Form.Item
            label="发起单位"
            name="unit"
            rules={[{ required: true, message: '请输入发起单位!' }]}
          >
            <Input placeholder="请输入发起单位" />
          </Form.Item>
          <Form.Item
            label="评审指标"
            name="criteriaCode"
            rules={[{ required: true, message: '请选择评审指标!' }]}
          >
            <Select placeholder="请选择评审指标" allowClear>
              {criteriaList.map((item) => (
                <Option value={item.code} key={item.code}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            label="参与学段"
            name="grade"
            rules={[{ required: true, message: '请选择参与学段!' }]}
          >
            <Select
              placeholder="请选择参与学段"
              allowClear
              mode="multiple"
              onChange={gradeChange}
            >
              <Option value="">全部</Option>
              {gradeList.map((item) => (
                <Option value={item.dictKey} key={item.dictKey}>
                  {item.dictValue}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            label="参与机构"
            name="unitCode"
            rules={[{ required: true, message: '请选择参与机构!' }]}
          >
            <TreeSelect
              placeholder="请选择参与机构"
              multiple
              showCheckedStrategy={TreeSelect.SHOW_ALL}
              treeCheckable
              treeDefaultExpandAll
              treeCheckStrictly
              onChange={onChange}
            >
              {renderTree(unitList)}
            </TreeSelect>
          </Form.Item>
          <Form.Item
            label="状态"
            name="status"
            rules={[{ required: true, message: '请选择状态!' }]}
          >
            <Select placeholder="请选择状态" allowClear>
              <Option value="0">禁用</Option>
              <Option value="1">资料收集</Option>
              <Option value="2">专家评审</Option>
              <Option value="3">审核</Option>
              <Option value="4">归档</Option>
            </Select>
          </Form.Item>

          <Form.Item label="备注说明" name="desc">
            <TextArea rows={3} placeholder="请输入备注说明" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}

const mapStateToProps = ({
  evaluationModel
}: {
  evaluationModel: EvaluationStateType
}) => {
  return {
    evaluationModel
  }
}

export default connect(mapStateToProps)(memo(AddEvaluationPage))
